<?php

declare(strict_types=1);

namespace app\controller\admin;

use app\controller\admin\AdminBaseController;
use app\model\admin\SysMemberGroup as SysMemberGroupModel;
use think\facade\Db;
use think\Request;

class SysMemberGroup extends AdminBaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $field = "*";
        $data = SysMemberGroupModel::scope('where', $request->param())
            ->scope('dataFilter')
            ->field($field)
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        return successPage($data);
    }

    public function show(Request $request)
    {
        $id = $request->param('id', 0);
        $data = SysMemberGroupModel::where('id', $id)->scope('dataFilter')->find();

        return success($data);
    }


    public function save(Request $request)
    {
        $param = $request->param();

        if (isset($param['id'])) {
            unset($param['id']);
        }

        $data = SysMemberGroupModel::create($param);
        $user_id = $data->id;
        return $user_id ? success([], "新增成功") : error('操作失败');
    }

    public function update(Request $request)
    {
        $param = $request->except(['password', 'login_ip', 'login_time', 'create_by']);
        $id = $param['id'];
        if (isset($param['id'])) {
            unset($param['id']);
        }


        $model = SysMemberGroupModel::where('id', $id)->scope('dataFilter')->find();

        $msg = 'success';

        $ret = $model->save($param);
        return $ret ? success([], "更新成功") : error($msg);
    }


    public function delete(Request $request)
    {
        $id = $request->param('id', '');
        if (!$id) {
            return error('缺少必要参数');
        }

        $ids = explode(',', $id);
        if (in_array(1, $ids)) {
            return error('包含不可删除数据');
        }

        Db::startTrans();
        $msg = 'success';
        try {
            $ret = SysMemberGroupModel::destroy($ids);
            DB::table('member_user')->whereIn('group_id', $ids)->delete();
            $result = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $result = false;
            $msg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $result ? success([], "删除成功") : error($msg);
    }
}
